using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using GomokuGame.AI;

namespace GomokuGame
{
    /// <summary>
    /// 游戏回放控制窗体
    /// </summary>
    public partial class ReplayForm : Form
    {
        private GameReplayManager replayManager;
        private GameRecordManager recordManager;
        private Form1 mainForm;
        
        // UI控件
        private ListBox listBoxRecords;
        private Button btnLoad;
        private Button btnDelete;
        private Button btnPlay;
        private Button btnPause;
        private Button btnStop;
        private Button btnPrevious;
        private Button btnNext;
        private Button btnFastForward;
        private Button btnFastRewind;
        private TrackBar trackBarProgress;
        private Label lblProgress;
        private Label lblStatus;
        private ComboBox comboBoxSpeed;
        private Button btnExportSGF;
        private Button btnClose;
        
        public ReplayForm(Form1 mainForm)
        {
            this.mainForm = mainForm;
            this.recordManager = mainForm.GetGameEngine().GetRecordManager();
            this.replayManager = new GameReplayManager(mainForm.GetGameEngine());
            
            InitializeComponent();
            InitializeReplayManager();
            LoadGameRecords();
        }
        
        private void InitializeComponent()
        {
            this.Text = "游戏回放";
            this.Size = new Size(600, 500);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            
            // 创建控件
            CreateControls();
            LayoutControls();
            
            // 绑定事件
            BindEvents();
        }
        
        private void CreateControls()
        {
            // 记录列表
            listBoxRecords = new ListBox
            {
                Dock = DockStyle.Top,
                Height = 200,
                SelectionMode = SelectionMode.One
            };
            
            // 按钮
            btnLoad = new Button { Text = "加载", Width = 80 };
            btnDelete = new Button { Text = "删除", Width = 80 };
            btnPlay = new Button { Text = "播放", Width = 80 };
            btnPause = new Button { Text = "暂停", Width = 80 };
            btnStop = new Button { Text = "停止", Width = 80 };
            btnPrevious = new Button { Text = "上一步", Width = 80 };
            btnNext = new Button { Text = "下一步", Width = 80 };
            btnFastForward = new Button { Text = "快进", Width = 80 };
            btnFastRewind = new Button { Text = "快退", Width = 80 };
            btnExportSGF = new Button { Text = "导出SGF", Width = 80 };
            btnClose = new Button { Text = "关闭", Width = 80 };
            
            // 进度条
            trackBarProgress = new TrackBar
            {
                Minimum = 0,
                Maximum = 100,
                TickFrequency = 10,
                Width = 400
            };
            
            // 标签
            lblProgress = new Label { Text = "进度: 0%", AutoSize = true };
            lblStatus = new Label { Text = "就绪", AutoSize = true };
            
            // 速度选择
            comboBoxSpeed = new ComboBox
            {
                DropDownStyle = ComboBoxStyle.DropDownList,
                Width = 100
            };
            comboBoxSpeed.Items.AddRange(new object[] { "0.1秒/步", "0.5秒/步", "1秒/步", "2秒/步", "5秒/步" });
            comboBoxSpeed.SelectedIndex = 2; // 默认1秒/步
        }
        
        private void LayoutControls()
        {
            // 主面板
            var mainPanel = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 1,
                RowCount = 4,
                Padding = new Padding(10)
            };
            
            // 记录列表区域
            var recordsPanel = new Panel { Dock = DockStyle.Top, Height = 220 };
            recordsPanel.Controls.Add(listBoxRecords);
            
            var recordsButtonPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Bottom,
                Height = 40,
                FlowDirection = FlowDirection.LeftToRight
            };
            recordsButtonPanel.Controls.AddRange(new Control[] { btnLoad, btnDelete, btnExportSGF });
            recordsPanel.Controls.Add(recordsButtonPanel);
            
            // 控制按钮区域
            var controlPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Top,
                Height = 50,
                FlowDirection = FlowDirection.LeftToRight
            };
            controlPanel.Controls.AddRange(new Control[] { 
                btnPlay, btnPause, btnStop, btnPrevious, btnNext, btnFastForward, btnFastRewind 
            });
            
            // 进度区域
            var progressPanel = new Panel { Dock = DockStyle.Top, Height = 60 };
            progressPanel.Controls.Add(trackBarProgress);
            progressPanel.Controls.Add(lblProgress);
            progressPanel.Controls.Add(lblStatus);
            
            // 速度控制区域
            var speedPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Top,
                Height = 40,
                FlowDirection = FlowDirection.LeftToRight
            };
            speedPanel.Controls.Add(new Label { Text = "播放速度:", AutoSize = true });
            speedPanel.Controls.Add(comboBoxSpeed);
            speedPanel.Controls.Add(btnClose);
            
            // 添加到主面板
            mainPanel.Controls.Add(recordsPanel, 0, 0);
            mainPanel.Controls.Add(controlPanel, 0, 1);
            mainPanel.Controls.Add(progressPanel, 0, 2);
            mainPanel.Controls.Add(speedPanel, 0, 3);
            
            this.Controls.Add(mainPanel);
        }
        
        private void BindEvents()
        {
            // 按钮事件
            btnLoad.Click += BtnLoad_Click;
            btnDelete.Click += BtnDelete_Click;
            btnPlay.Click += BtnPlay_Click;
            btnPause.Click += BtnPause_Click;
            btnStop.Click += BtnStop_Click;
            btnPrevious.Click += BtnPrevious_Click;
            btnNext.Click += BtnNext_Click;
            btnFastForward.Click += BtnFastForward_Click;
            btnFastRewind.Click += BtnFastRewind_Click;
            btnExportSGF.Click += BtnExportSGF_Click;
            btnClose.Click += BtnClose_Click;
            
            // 进度条事件
            trackBarProgress.ValueChanged += TrackBarProgress_ValueChanged;
            
            // 速度选择事件
            comboBoxSpeed.SelectedIndexChanged += ComboBoxSpeed_SelectedIndexChanged;
            
            // 回放管理器事件
            replayManager.ReplayEvent += ReplayManager_ReplayEvent;
        }
        
        private void InitializeReplayManager()
        {
            // 设置初始播放速度
            SetPlaybackSpeed();
        }
        
        private void LoadGameRecords()
        {
            listBoxRecords.Items.Clear();
            
            try
            {
                var records = recordManager.GetAllGameRecords();
                foreach (var record in records)
                {
                    string displayText = $"{record.GameInfo.StartTime:yyyy-MM-dd HH:mm} - " +
                                       $"{record.GameInfo.BlackPlayer} vs {record.GameInfo.WhitePlayer} - " +
                                       $"{record.MoveCount}步";
                    
                    if (record.Result.Winner != PieceType.Empty)
                    {
                        string winner = record.Result.Winner == PieceType.Black ? "黑胜" : "白胜";
                        displayText += $" - {winner}";
                    }
                    else if (record.Result.IsDraw)
                    {
                        displayText += " - 平局";
                    }
                    
                    listBoxRecords.Items.Add(new ListBoxItem(displayText, record));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载游戏记录失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        private void SetPlaybackSpeed()
        {
            int speed;
            switch (comboBoxSpeed.SelectedIndex)
            {
                case 0: speed = 100; break;   // 0.1秒
                case 1: speed = 500; break;   // 0.5秒
                case 2: speed = 1000; break;  // 1秒
                case 3: speed = 2000; break;  // 2秒
                case 4: speed = 5000; break;  // 5秒
                default: speed = 1000; break;
            }
            
            replayManager.SetPlaybackSpeed(speed);
        }
        
        #region 事件处理
        
        private void BtnLoad_Click(object sender, EventArgs e)
        {
            if (listBoxRecords.SelectedItem is ListBoxItem item && item.RecordInfo != null)
            {
                try
                {
                    var record = recordManager.LoadGameRecord(item.RecordInfo.FilePath);
                    replayManager.LoadGameRecord(record);
                    
                    // 更新进度条
                    trackBarProgress.Maximum = record.Moves.Count;
                    trackBarProgress.Value = 0;
                    
                    lblStatus.Text = $"已加载: {record.GameInfo.BlackPlayer} vs {record.GameInfo.WhitePlayer}";
                    UpdateProgressLabel();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"加载游戏记录失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        
        private void BtnDelete_Click(object sender, EventArgs e)
        {
            if (listBoxRecords.SelectedItem is ListBoxItem item && item.RecordInfo != null)
            {
                if (MessageBox.Show("确定要删除这个游戏记录吗？", "确认删除", 
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    try
                    {
                        recordManager.DeleteGameRecord(item.RecordInfo.FilePath);
                        LoadGameRecords();
                        lblStatus.Text = "记录已删除";
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"删除游戏记录失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
        
        private void BtnPlay_Click(object sender, EventArgs e)
        {
            replayManager.StartPlayback();
        }
        
        private void BtnPause_Click(object sender, EventArgs e)
        {
            replayManager.PausePlayback();
        }
        
        private void BtnStop_Click(object sender, EventArgs e)
        {
            replayManager.StopPlayback();
        }
        
        private void BtnPrevious_Click(object sender, EventArgs e)
        {
            replayManager.PreviousMove();
        }
        
        private void BtnNext_Click(object sender, EventArgs e)
        {
            replayManager.NextMove();
        }
        
        private void BtnFastForward_Click(object sender, EventArgs e)
        {
            replayManager.FastForward(5);
        }
        
        private void BtnFastRewind_Click(object sender, EventArgs e)
        {
            replayManager.FastRewind(5);
        }
        
        private void BtnExportSGF_Click(object sender, EventArgs e)
        {
            if (listBoxRecords.SelectedItem is ListBoxItem item && item.RecordInfo != null)
            {
                try
                {
                    var record = recordManager.LoadGameRecord(item.RecordInfo.FilePath);
                    string sgfContent = record.ExportToSGF();
                    
                    using (var saveDialog = new SaveFileDialog())
                    {
                        saveDialog.Filter = "SGF文件 (*.sgf)|*.sgf|所有文件 (*.*)|*.*";
                        saveDialog.FileName = Path.GetFileNameWithoutExtension(item.RecordInfo.FileName) + ".sgf";
                        
                        if (saveDialog.ShowDialog() == DialogResult.OK)
                        {
                            File.WriteAllText(saveDialog.FileName, sgfContent, System.Text.Encoding.UTF8);
                            MessageBox.Show("SGF文件导出成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"导出SGF失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        
        private void BtnClose_Click(object sender, EventArgs e)
        {
            replayManager.StopPlayback();
            this.Close();
        }
        
        private void TrackBarProgress_ValueChanged(object sender, EventArgs e)
        {
            if (replayManager.GameRecord != null)
            {
                int moveIndex = trackBarProgress.Value - 1;
                replayManager.GoToMove(moveIndex);
            }
        }
        
        private void ComboBoxSpeed_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetPlaybackSpeed();
        }
        
        private void ReplayManager_ReplayEvent(object sender, ReplayEventArgs e)
        {
            // 在UI线程中更新界面
            this.BeginInvoke(new Action(() =>
            {
                lblStatus.Text = e.Message;
                
                if (e.EventType == ReplayEventType.MoveChanged)
                {
                    trackBarProgress.Value = e.CurrentMoveIndex + 1;
                    UpdateProgressLabel();
                }
                else if (e.EventType == ReplayEventType.Loaded)
                {
                    trackBarProgress.Maximum = e.TotalMoves;
                    trackBarProgress.Value = 0;
                    UpdateProgressLabel();
                }
            }));
        }
        
        private void UpdateProgressLabel()
        {
            if (replayManager.GameRecord != null)
            {
                double progress = replayManager.GetPlaybackProgress();
                lblProgress.Text = $"进度: {progress:F1}% ({replayManager.CurrentMoveIndex + 1}/{replayManager.GameRecord.Moves.Count})";
            }
        }
        
        #endregion
        
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            replayManager.Dispose();
            base.OnFormClosing(e);
        }
    }
    
    /// <summary>
    /// 列表框项，用于存储记录信息
    /// </summary>
    public class ListBoxItem
    {
        public string DisplayText { get; set; }
        public GameRecordInfo RecordInfo { get; set; }
        
        public ListBoxItem(string displayText, GameRecordInfo recordInfo)
        {
            DisplayText = displayText;
            RecordInfo = recordInfo;
        }
        
        public override string ToString()
        {
            return DisplayText;
        }
    }
} 